package algorithms.sorts;

import java.util.Arrays;

public class SelectSort {

    public static void main(String[] args) {
        int[] arr = {1, 6, 3, -13, 8, 10, -100};
        selectSort2(arr);
        System.out.println(Arrays.toString(arr));
    }

    private static void selectSort(int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            int index = i;

            for (int j = i + 1; j < arr.length; j++) {
                if (arr[index] > arr[j]) {
                    index = j;
                }
            }
            int temp = arr[i];
            arr[i] = arr[index];
            arr[index] = temp;
        }
    }

    private static void selectSort2(int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            int minIndex = i;
            int end = arr.length - i - 1;
            int maxIndex = end;

            for (int j = i + 1; j <= end; j++) {
                if (arr[minIndex] > arr[j]) {//i+1->end
                    minIndex = j;
                }
                if (arr[maxIndex] < arr[j - 1]) {//i->end-1
                    maxIndex = j - 1;
                }
            }
            int temp;
            if (i != minIndex) {
                temp = arr[i];

                arr[i] = arr[minIndex];
                arr[minIndex] = temp;

                if (i == maxIndex) {//此时最大值索引已经调整到minIndex位置，将maxIndex置为minIndex
                    maxIndex = minIndex;
                }
            }
            if (end != maxIndex) {
                temp = arr[end];
                arr[end] = arr[maxIndex];
                arr[maxIndex] = temp;
            }

        }
    }
}
